package com.zsd.android.common

import com.zsd.android.common.bean.ApiBean
import com.zsd.android.common.utils.MLog
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okio.Buffer
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.RuntimeException
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

class ModelFactory private constructor() {

    private val BASE_URL = "https://www.baidu.com/"
    private val apiMap: HashMap<Class<*>, ApiBean<*>>
    private val mRetrofit: Retrofit

    init {
        apiMap = HashMap()

        var client = OkHttpClient.Builder()
            .readTimeout(15, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(createLogInterceptor())
            .build()

        mRetrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
    }

    //添加接口请求日志拦截器
    private fun createLogInterceptor(): Interceptor {
        return Interceptor { chain ->
            val connection = chain.connection()
            val protocol = if (connection != null) connection.protocol() else Protocol.HTTP_1_1
            val request = chain.request()
            val url = request.url()
            MLog.mLog(request.method() + " url = " + url.toString() + " " + protocol)
            val body = request.body()
            if (body is FormBody) {
                val size = body.size()
                for (i in 0 until size) {
                    val name = body.name(i)
                    val value = body.value(i)
                    MLog.mLog("name = $name, value = $value")
                }
            } else {
                val buffer = Buffer()
                body!!.writeTo(buffer)
                val s = buffer.readUtf8()
                MLog.mLog("request = $s")
            }
            val proceed = chain.proceed(request)
            val responseBody = proceed.body()
            val source = responseBody!!.source()
            source.request(java.lang.Long.MAX_VALUE)
            val buffer = source.buffer()
            val charset = Charset.forName("UTF-8")
            val s = buffer.clone().readString(charset)
            MLog.mLog("\nresult = $s")
            MLog.mLog("<-- END HTTP (" + buffer.size() + "-byte body)")
            proceed
        }
    }

    companion object Factory {

        @Volatile
        private var instance: ModelFactory? = null

        fun getInstance(): ModelFactory? {
            var factory = instance
            if (factory == null) {
                synchronized(ModelFactory::class) {
                    if (factory == null) {
                        factory = ModelFactory()
                        instance = factory
                    }
                }
            }
            return factory
        }
    }

    /**
     * 创建接口Api，结合Retrofit使用
     *  @param clazz 接口类的class对象
     */
    fun <T> createApi(clazz: Class<T>): T {
        if (clazz == null) {
            throw RuntimeException("Api接口不能为空")
        }
        var apiBean = apiMap.get(clazz)
        if (apiBean == null) {
            apiBean = ApiBean<T>()
            apiBean.api = mRetrofit.create(clazz)
            apiMap.put(clazz, apiBean)
        }
        return apiBean.api as T
    }
}